<template>
  <div class="van-uploader uploader-align">
    <div class="van-uploader__wrapper">
      <template v-if="modelValue">
        <div class="van-uploader__preview">
          <div class="van-image van-uploader__preview-image">
            <img :src="modelValue" class="van-image__img" style="object-fit: cover" />
          </div>
          <div role="button" class="van-uploader__preview-delete" @click="bindDelete()">
            <i class="van-badge__wrapper van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
          </div>
        </div>
      </template>
      <div class="van-uploader__upload" v-if="!modelValue" @click="addImage()">
        <i class="van-badge__wrapper van-icon van-icon-photograph van-uploader__upload-icon"></i>
        <div class="van-uploader__input"></div>
      </div>
    </div>
    <!-- 提示信息 -->
    <div class="tip">{{ tip }}</div>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance, onMounted, watch } from 'vue'

const { proxy } = getCurrentInstance()

const props = defineProps({
  modelValue: String,
  wx: Object,
  tip: String
})
const emit = defineEmits(['update:modelValue', 'add', 'delete'])
const weChat = ref(null)

onMounted(() => {
  weChat.value = props.wx
})

watch(
  () => props.wx,
  (val) => {
    weChat.value = val
  }
)

/** 添加图片 */
const addImage = () => {
  weChat.value.checkJsApi({
    jsApiList: ['chooseImage', 'getLocalImgData'],
    success: function (suc) {
      if (suc.checkResult.chooseImage && suc.checkResult.getLocalImgData) {
        weChat.value.chooseImage({
          count: 1,
          success: function (res) {
            let localIds = res.localIds // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            getImgData(localIds)
          },
          fail: function (res) {
            console.log('选取失败', res)
          }
        })
      }
    },
    fail: function () {
      proxy.$toast('暂不支持上传图片')
    }
  })
}

/**
 * 删除图片
 * @param {*} index
 */
const bindDelete = () => {
  emit('update:modelValue', null)
}

/**
 * 获取本地图片
 * @param {*} localIds
 */
const getImgData = (localIds) => {
  weChat.value.getLocalImgData({
    localId: localIds[0], // 图片的localID
    success: function (res) {
      const localData = res.localData
      let imageBase64 = ''
      if (localData.indexOf('data:image') === 0) {
        imageBase64 = localData
      } else {
        imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
      }
      emit('update:modelValue', imageBase64)
    },
    fail: function (res) {
      console.log('获取base64失败', res)
    }
  })
}

</script>
<style lang="less" scoped>
.uploader-align {
  text-align: right;
  .van-uploader__wrapper {
    justify-content: flex-end;

    .van-uploader__upload {
      margin: 0 0 8px 8px;
    }
    .van-uploader__preview {
      margin: 0 0 8px 8px;
    }
  }
}
.tip {
  font-size: 10px;
  color: var(--font-hc);
  text-align: left;
}
</style>
